﻿using System;
using System.Collections;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Claims;
using System.Collections.Generic;

namespace AIS.SharePoint.AspNetFBA.Layouts.AIS.SharePoint.AspNetFBA
{
    public partial class UserList : LayoutsPageBase
    {
        private const string _VIEWSTATE_SORTDIRECTION = "__AISSortDirection";
        private const string _VIEWSTATE_SORTEXPRESSION = "__AISSortExpresion";

        /// <summary>
        /// Required rights for the page
        /// </summary>
        protected override SPBasePermissions RightsRequired
        {
            get
            {
                return SPBasePermissions.ManagePermissions | SPBasePermissions.BrowseUserInfo;
            }
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            try
            {
                DataView DataView = new System.Data.DataView(GetUserTable());

                // Perform sorting logic
                if ((ViewState[_VIEWSTATE_SORTEXPRESSION] != null) && (ViewState[_VIEWSTATE_SORTDIRECTION] != null))
                {
                    try
                    {
                        DataView.Sort = ViewState[_VIEWSTATE_SORTEXPRESSION].ToString() + " " + ViewState[_VIEWSTATE_SORTDIRECTION].ToString();
                    }
                    catch (Exception ex)
                    {
                        Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.Unexpected, Code.Log.Category.Processing);
                    }
                }
                gvUserList.DataSource = DataView;
                gvUserList.DataBind();
                base.Render(writer);
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Rendering);
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public void gvUserList_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                // Store sort data to facilitate direction changes when
                // the sort column is clicked a second (or N) time
                string SortExpression = "";
                string SortDirection = "ASC";
                if (ViewState[_VIEWSTATE_SORTEXPRESSION] != null) { SortExpression = ViewState[_VIEWSTATE_SORTEXPRESSION].ToString(); }
                if (ViewState[_VIEWSTATE_SORTDIRECTION] != null) { SortDirection = ViewState[_VIEWSTATE_SORTDIRECTION].ToString(); }

                if (e.SortExpression == SortExpression)
                {
                    // Sorting the same field, change directions
                    SortDirection = (SortDirection == "ASC") ? "DESC" : "ASC";
                }
                else
                {
                    // New Sort
                    SortExpression = e.SortExpression;
                }

                // Update view state
                ViewState[_VIEWSTATE_SORTDIRECTION] = SortDirection;
                ViewState[_VIEWSTATE_SORTEXPRESSION] = SortExpression;
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Processing);
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }

        private DataTable GetUserTable()
        {
            DataTable DataTable = new DataTable();
            try
            {
                Code.Claims ClaimsHandler = new Code.Claims();

                DataTable.Columns.Add("FullName", typeof(string));                  // 0
                DataTable.Columns.Add("UserName", typeof(string));                  // 1
                DataTable.Columns.Add("EMail", typeof(string));                     // 2
                DataTable.Columns.Add("CreatedOn", typeof(DateTime));               // 3
                DataTable.Columns.Add("LastLogon", typeof(DateTime));               // 4
                DataTable.Columns.Add("InSharePoint", typeof(Boolean));             // 5

                // Build query to locate all SP users
                SPQuery Query = new SPQuery();
                Query.Query = string.Format(
                     "<Where>" +
                         "<And>" +
                             "<Eq><FieldRef Name='ContentType' /><Value Type='Text'>Person</Value></Eq>" +
                             "<Contains><FieldRef Name='Name' /><Value Type='Text'>{0}</Value></Contains>" +
                         "</And>" +
                     "</Where>" +
                     "<OrderBy>" +
                         "<FieldRef Name='LinkTitle' />" +
                     "</OrderBy>", ClaimsHandler.FormsMembersShipProviderName);

                Query.ViewFields = "<FieldRef Name='Name' /><FieldRef Name='LinkTitle' /><FieldRef Name='Email' /><FieldRef Name='Modified' /><FieldRef Name='Created' />";

                SPList list = SPContext.Current.Site.RootWeb.Lists[SPUtility.GetLocalizedString("$Resources:userinfo_schema_listtitle", "core", SPContext.Current.Site.RootWeb.Language)];
                DataTable UserTable = list.GetItems(Query).GetDataTable();

                // Get the ordinals to enhance lookup performance
                int UserNameColumn = UserTable.Columns["Name"].Ordinal;
                int TitleNameColumn = UserTable.Columns["Title"].Ordinal;

                foreach (MembershipUser User in Membership.GetAllUsers())
                {
                    DataRow NewRow = DataTable.NewRow();
                    DataTable.Rows.Add(NewRow);

                    NewRow[1] = User.UserName;
                    NewRow[2] = User.Email;
                    NewRow[3] = User.CreationDate;
                    NewRow[4] = User.LastLoginDate;
                    NewRow[5] = false;

                    SPClaim UserClaim = ClaimsHandler.GetClaimForUserName(User.UserName);
                    string ClaimBasedUserName = SPClaimProviderManager.Local.EncodeClaim(UserClaim).ToLower();
                    foreach (DataRow Row in UserTable.Rows)
                    {
                        string SPUserName = Row[UserNameColumn].ToString();
                        if (ClaimBasedUserName == SPUserName.ToLower())
                        {
                            NewRow[0] = Row[TitleNameColumn].ToString();
                            NewRow[5] = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Processing);
                SPUtility.TransferToErrorPage(ex.Message);
            }
            return DataTable;
        }
    }
}
